package com.study.test.config;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Properties;

@Slf4j
@Component
public class KaptchaConfig {
    @Bean
    public DefaultKaptcha getKaptcheCode(){
        DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
        Properties properties = new Properties();
        properties.setProperty("kaptcha.border","no");
        properties.setProperty("kaptcha.textproducer.font.color","black");
        properties.setProperty("kaptcha.image.width", "100");
        properties.setProperty("kaptcha.image.height", "36");
        properties.setProperty("kaptcha.textproducer.font.size", "30");
        properties.setProperty("kaptcha.obscurificator.impl", "com.google.code.kaptcha.impl.ShadowGimpy");
        properties.setProperty("kaptche.session.key","code");
        properties.setProperty("kaptcha.noise.impl", "com.google.code.kaptcha.impl.NoNoise");
        properties.setProperty("kaptcha.background.clear.from", "232,240,254");
        properties.setProperty("kaptcha.background.clear.to", "232,240,254");
        properties.setProperty("kaptcha.textproducer.char.length", "4");
        properties.setProperty("kaptcha.textproducer.font.names", "彩云,宋体,楷体,微软雅黑");
        Config config = new Config(properties);
       defaultKaptcha.setConfig(config);
       return defaultKaptcha;
    }

    public static boolean validate(String registerCode, HttpServletRequest request){
        HttpSession session = request.getSession();
        String captcha = (String) session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
        if(StringUtils.isEmpty(registerCode)){
            return false;
        }
        boolean result = registerCode.equalsIgnoreCase(captcha);
        if(result){
            log.info("验证码比对成功");
            request.getSession().removeAttribute(Constants.KAPTCHA_SESSION_CONFIG_KEY);
        }
        return result;
    }
}
